package com.lntea.redis;

import org.junit.Before;
import org.junit.Test;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPubSub;

public class PubSubDemo {
	Jedis jedis;
	JedisPubSub jedisPubSub;
	
	@Before
	public void connect(){
		jedis = new Jedis("192.168.1.108", 6379);
		jedisPubSub = new JedisPubSub() {
			
			@Override
			public void onUnsubscribe(String channel, int subscribedChannels) {
				System.out.println("unsubscribe channel "+channel+",id="+subscribedChannels);
			}
			
			@Override
			public void onSubscribe(String channel, int subscribedChannels) {
				System.out.println("subscribe channel "+channel+",id="+subscribedChannels);
			}
			
			@Override
			public void onPUnsubscribe(String pattern, int subscribedChannels) {
				System.out.println("punsubscribe channel "+pattern+",id="+subscribedChannels);
			}
			
			@Override
			public void onPSubscribe(String pattern, int subscribedChannels) {
				System.out.println("psubscribe channel "+pattern+",id="+subscribedChannels);
			}
			
			@Override
			public void onPMessage(String pattern, String channel, String message) {
				System.out.println("pmessage "+message+" from channel "+channel+" pattern "+pattern);
			}
			
			@Override
			public void onMessage(String channel, String message) {
				System.out.println("message "+message+" from channel "+channel);
			}
		};
	}
	
	@Test
	public void subscribe(){
		//subscribe channels
		jedis.subscribe(jedisPubSub, "foo","bar");
	}
	
	@Test
	public void psubscribe(){
		//subscribe channels by pattern
		jedis.psubscribe(jedisPubSub, "f*","t*");
	}
	
	@Test
	public void publish(){
		//publish message specifying channel string or pattern
		jedis.publish("foo", "hello foo");
	}
}
